package com.order.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.order.dao.User;
import com.order.exception.ServiceException;
import com.order.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    public boolean preHandle(HttpServletRequest request , HttpServletResponse response , Object handler){
        String token = request.getHeader("token");//header 传过来的参数
        if(StrUtil.isBlank(token)){
            token = request.getParameter("token");//url 传过来的参数
        }
        //不是映射到方法直接通过
        if(handler instanceof HandlerMethod){
            AuthAccess annotation = ( (HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if(annotation != null){
                return true;
            }
        }
        //执行认证
        if(StrUtil.isBlank(token)){
            /*log.info("经过0");*/
            throw  new ServiceException("401","请登录");
        }
        //获取token中的user.id
        String userId;
        try{
            /*log.info("经过1");*/
            userId = JWT.decode(token).getAudience().get(0);//对JSON token 进行解码 获取第一个参数id
        } catch (JWTDecodeException j){
            throw  new ServiceException("401","请登录");
        }
        //根据token中的userId查询数据库
        User user = userMapper.getById(Integer.parseInt(userId));
        /*log.info("经过2");*/
        if(user == null){
            throw new ServiceException("401","请登录");
        }
        //通过用户密码加密后，生成一个验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try{
            /*log.info("经过3");*/
            jwtVerifier.verify(token) ;
        }catch (JWTVerificationException j){
            throw new ServiceException("401","请登录");
        }
        return true;
    }

}
